package com.tstudy.laoshibang.db;

import java.sql.SQLException;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.tstudy.laoshibang.mode.Category;
import com.tstudy.laoshibang.mode.City;
import com.tstudy.laoshibang.mode.CommunityMessage;
import com.tstudy.laoshibang.mode.Dictionary;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.SearchHistory;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.utils.LogUtil;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DBHelper extends OrmLiteSqliteOpenHelper {

	private final static String DATABASE_NAME = "laoshibang.db";
	private final static int DATABASE_VERSION = 4;

	public DBHelper(Context context) {
		this(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	public DBHelper(Context context, String databaseName,
			CursorFactory factory, int databaseVersion) {
		super(context, DATABASE_NAME, factory, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource cs) {
		LogUtil.d(DATABASE_NAME + "oncreate database");
		try {
			TableUtils.createTable(cs,City.class);
			TableUtils.createTable(cs,SearchHistory.class);
			TableUtils.createTable(cs,Category.class);
			TableUtils.createTable(cs,Dictionary.class);
			TableUtils.createTable(cs,User.class);
			TableUtils.createTable(cs,TGroup.class);
			TableUtils.createTable(cs,CommunityMessage.class);
		} catch (SQLException e) {
			LogUtil.e(DBHelper.class.getName() + " 创建数据库失败");
			e.printStackTrace();
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource cs, int arg2,
			int arg3) {
		try {
			LogUtil.d( DATABASE_NAME + "onupgrade database");
			TableUtils.dropTable(connectionSource, City.class, true);
			TableUtils.dropTable(connectionSource,SearchHistory.class,true);
			TableUtils.dropTable(connectionSource,Dictionary.class,true);
			TableUtils.dropTable(connectionSource,Category.class,true);
			TableUtils.dropTable(connectionSource,User.class,true);
			TableUtils.dropTable(connectionSource, CommunityMessage.class, true);
			TableUtils.dropTable(connectionSource, TGroup.class, true);
			onCreate(db, connectionSource);
		} catch (Exception e) {
			LogUtil.d(DBHelper.class.getName() + "更新数据库失败");
			e.printStackTrace();
		}
	}

}
